// src/api/base.js
import axios from 'axios'
import { apiConfig } from '@/config/api'

// 创建并导出实例
export const apiClient = axios.create({
    baseURL: apiConfig.baseURL,
    timeout: apiConfig.timeout,
    headers: { 'Content-Type': 'application/json' }
  })

// 请求拦截器：添加Token
apiClient.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器：统一处理错误
apiClient.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.reload()
    }
    // 对于blob响应，不要修改错误信息
    if (error.config?.responseType === 'blob') {
      return Promise.reject(error)
    }
    // 关键修改：返回错误信息
    return Promise.reject(error.response?.data?.message || '请求失败')
  }
)